/**
 * eCommerce Application Sample for J2EE Training 
 * Implementation of EcomCustomerBean
 * @author Fabienne Boyer - Didier Donsez
 * may 2006
 */

package ecom.beans;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.SessionSynchronization;
import javax.ejb.Stateful;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ecom.pojos.*;

@Stateful
@Remote(EcomCustomerRemote.class)
public class EcomCustomerBean implements EcomCustomerRemote {

	@PersistenceContext
	private EntityManager entityManager = null;

	@EJB
	private CartLocal cart;

	public Vector<Product> getAllProducts() {
		Query q = entityManager.createQuery("SELECT p FROM ProductBean p");
		List<ProductBean> prods = q.getResultList();
		return mkProductVector(prods);
	}

	private Vector<Product> mkProductVector(List<ProductBean> pbl) {
		Vector<Product> res = new Vector<Product>();
		Iterator<ProductBean> ite = pbl.iterator();

		while (ite.hasNext()) {
			ProductBean cur = ite.next();
			Query q2 = entityManager
					.createQuery("SELECT q FROM TechQuestionBean q WHERE q.productId LIKE :ref");
			List<TechQuestionBean> questions = q2.setParameter("ref",
					cur.getReference()).getResultList();
			Vector<TechQuestion> tq = getTechQuestions(questions);

			q2 = entityManager
					.createQuery("SELECT co FROM CustomerOpinionBean co WHERE co.productId LIKE :ref");
			List<CustomerOpinionBean> opinions = q2.setParameter("ref",
					cur.getReference()).getResultList();
			Vector<CustomerOpinion> co = getCustomerOpinions(opinions);

			Product p = new Product(cur.getName(), cur.getReference(), cur
					.getDescription(), cur.getStock(), cur.getBrand(), cur
					.getCategory(), cur.getEuroPrice(), tq, co);

			res.add(p);
		}

		return res;

	}

	private Vector<TechQuestion> getTechQuestions(List<TechQuestionBean> q) {
		Vector<TechQuestion> res = new Vector<TechQuestion>();
		Iterator<TechQuestionBean> ite = q.iterator();

		while (ite.hasNext()) {
			TechQuestionBean cur = ite.next();
			TechQuestion tq = new TechQuestion(cur.getQuestion(), cur
					.getReponse());
			res.add(tq);
		}

		return res;
	}

	private Vector<CustomerOpinion> getCustomerOpinions(
			List<CustomerOpinionBean> col) {
		Vector<CustomerOpinion> res = new Vector<CustomerOpinion>();
		Iterator<CustomerOpinionBean> ite = col.iterator();

		while (ite.hasNext()) {
			CustomerOpinionBean cur = ite.next();
			CustomerOpinion co = new CustomerOpinion(cur.getNote(), cur
					.getCommentaire(), cur.getIdClient());
			res.add(co);
		}

		return res;
	}

	public Vector<Product> getProductsByCat(String cat) {
		Query q = entityManager
				.createQuery("SELECT p FROM ProductBean p WHERE p.category LIKE :cat");
		List<ProductBean> prods = q.setParameter("cat", cat).getResultList();
		return mkProductVector(prods);
	}

	public Vector<Product> getProductsByBrand(String brand) {
		Query q = entityManager
				.createQuery("SELECT p FROM ProductBean p WHERE p.brand LIKE :brand");
		List<ProductBean> prods = q.setParameter("brand", brand)
				.getResultList();
		return mkProductVector(prods);
	}

	public Vector<Product> getProductsByKeyword(String keyword) {
		Vector<Product> res = new Vector<Product>();
		Vector<Product> pv = getAllProducts();
		Iterator<Product> ite = pv.iterator();

		keyword = keyword.toLowerCase();

		while (ite.hasNext()) {
			Product cur = ite.next();
			if (cur.getDescription().contains(keyword)
					|| cur.getName().contains(keyword)
					|| cur.getMarque().contains(keyword))
				res.add(cur);
		}

		return res;
	}

	public void cartAddProduct(String productId) {
		cart.putInto(productId);

	}

	public void cartSetCustomer(String email) {
		CustomerBean customer = entityManager.find(CustomerBean.class,
				email);
		cart.setCustomer(customer);
	}

	public Vector<Product> cartListProduct() {
		List<CartProductBean> prods = cart.listOfProducts();
		LinkedList<ProductBean> pbl = new LinkedList<ProductBean>();
		Iterator<CartProductBean> ite = prods.iterator();
		
		Vector<Product> res = new Vector<Product>();
		while (ite.hasNext()) {
			CartProductBean curCPB = ite.next();
			ProductBean cur = curCPB.getProductBean();
			Query q2 = entityManager
					.createQuery("SELECT q FROM TechQuestionBean q WHERE q.productId LIKE :ref");
			List<TechQuestionBean> questions = q2.setParameter("ref",
					cur.getReference()).getResultList();
			Vector<TechQuestion> tq = getTechQuestions(questions);

			q2 = entityManager
					.createQuery("SELECT co FROM CustomerOpinionBean co WHERE co.productId LIKE :ref");
			List<CustomerOpinionBean> opinions = q2.setParameter("ref",
					cur.getReference()).getResultList();
			Vector<CustomerOpinion> co = getCustomerOpinions(opinions);

			Product p = new Product(cur.getName(), cur.getReference(), cur
					.getDescription(), cur.getStock(), cur.getBrand(), cur
					.getCategory(), cur.getEuroPrice(), tq, co);
			
			p.setQuantity(curCPB.getQuantity());
			//System.err.println(p.getQuantity());
			res.add(p);
		}
		return res;
		
	}

	public void cartRemove(String ref) {
		cart.remove(ref);
	}

	public void cartEmpty() {
		cart.emptyCart();
	}

	public boolean cartOrder(String  email) {
		cartSetCustomer(email);
		return cart.ordering();
	}

	public void createTechQuestion(String ref, String question) {
		TechQuestionBean tqb = new TechQuestionBean(ref, question, null);
		entityManager.persist(tqb);
	}

	public Vector<TechQuestion> getTechQuestions(String ref) {

		Vector<TechQuestion> res = new Vector<TechQuestion>();

		Query q = entityManager.createNamedQuery("getQuestionsByProd");
		List<TechQuestionBean> tqbs = q.setParameter("prodId", ref)
				.getResultList();
		Iterator<TechQuestionBean> ite = tqbs.iterator();

		while (ite.hasNext()) {
			TechQuestionBean cur = ite.next();
			res.add(new TechQuestion(cur.getQuestion(), cur.getReponse()));
		}

		return res;
	}

}
